var ns,bmLocation,db;
var app = new Vue({
    el: '#app',
    data: {
        list: [],
        lists:[],
        form: {
            ID: 0,
            status: 0, //1-未完成 2-已完成
            StatusName: '全部',
            keywords: ''
        },
        PlanType: 1,
        total: {
            ProcessCount: 0,
            CompleteCount: 0
        },
        statusList: [
            { "ID": 0, "Name": "全部设备","count":0 },
            { "ID": 3, "Name": "未完成" ,"count":0},
            { "ID": 2, "Name": "已完成" ,"count":0},
            { "ID": 1, "Name": "异常" ,"count":0},
        ],
        // 全部的数量
        dataCount: 0,
        // 完成数量
        completeCount: 0,
        IsStartStatus:false,
        PlanStartTime:'',
        selectform:{},
        Longitude:'',
        Latitude:'',
        GPSLocation:'',
        plantaskform:{},
        UnStartlist:[],
        CompleteCountlist:[],
        AbnormalCounttlist:[],
        itemform:{},
    },
    methods: {
        get_item_data: function () {
            var that = this;
            let selplantasksql = `SELECT * FROM Sys_Plan WHERE ID=${that.form.ID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplantasksql
            }, function (ret, err) {
                if (ret.status) {
                    var list = ret.data;
                    if (list.length > 0) {
                        that.itemform =list[0];
                    }  
                }
            });
        },
        get_data: function () {
            var that = this;
            let selplantasksql = `SELECT * FROM Sys_PlanTask WHERE PlanTaskID=${that.form.ID}`;
            db.selectSql({
                name: 'prodemotest',
                sql: selplantasksql
            }, function (ret, err) {
                if (ret.status) {
                    // console.log(JSON.stringify(ret.data));
                    that.list = ret.data;
                    that.onClickStatus(0);
                    if(that.form.keywords.trim()!=''){
                        that.do_search();
                    }
                    if (that.list.length > 0) {
                        that.total = that.list[0];
                        setTimeout(function () {
                            that.do_update_count();//更新数量
                        }, 100)
                        //判断状态赋值
                        if (that.total.TaskStatus != 3) {
                            that.do_check_canstart();
                        }
                    }
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        do_search: function () {
            var that = this;
            let newlist = that.list.filter((val) => {
                return val.PatrolName.includes(that.form.keywords)||val.PatrolNumber.includes(that.form.keywords);
            });
            that.lists=newlist;
        },
        onClickStatus:function(ID){
            var that = this;
            that.form.status = ID;
            switch (that.form.status) {
                case 1:
                    that.lists=that.AbnormalCounttlist;
                    break;
                case 2:
                    that.lists=that.CompleteCountlist;
                    break;
                case 3:
                    that.lists=that.UnStartlist;
                    break;
                default:
                    that.lists=that.list;
                    break;
            }
        },
        do_check_canstart:function(){
            var that = this;
            let nowTime = moment().format('YYYY-MM-DD HH:mm');
            const diffStartTime = moment(that.total.StartTime).diff(moment(nowTime), 'seconds');
            if(diffStartTime>=0){
                that.IsStartStatus = true;
                that.PlanStartTime = that.total.StartTime;
                if (that.PlanStartTime) {
                    that.PlanStartTime = ns.SetTime_style(that.PlanStartTime);
                }
            }  
        },
        do_update_count:function(){
            var that = this;
            that.statusList[0].count = that.list.length;
            let UnStartlist = that.list.filter( (val) => {
                return val.TaskStatus!='3'|| (val.TaskStatus == '3'&&that.itemform.TaskStatus=='4');
            });
            let CompleteCountlist = that.list.filter( (val) => {
                return val.TaskStatus == '3' && that.itemform.TaskStatus != '4';
            });
            let AbnormalCounttlist = that.list.filter( (val) => {
                return val.TaskStatus=='3'&&val.CheckStatus=='2';
            });
            that.UnStartlist=UnStartlist;
            that.CompleteCountlist=CompleteCountlist;
            that.AbnormalCounttlist=AbnormalCounttlist;
            that.statusList[1].count = UnStartlist.length;
            that.statusList[2].count = CompleteCountlist.length;
            that.statusList[3].count = AbnormalCounttlist.length;

            let strsql=`UPDATE Sys_Plan SET completeCount=${CompleteCountlist.length},abnormalCount=${AbnormalCounttlist.length}  WHERE ID=${that.form.ID}`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strsql
                }, function (ret, err) {
                });
        },
        do_open_scan: function (item) {
            var that = this;
            ns.confirmPer('camera', function () {
                setTimeout(function () {
                    that.do_open_scan_start(item);
                }, 200)
            })
        },
        do_open_scan_start: function (item) {
            var that = this;
            ns.openFrame('scanner_frm', {
                type: 2,
                id: item.ID,
                EncriptID: item.EncriptID
            });
        },
        open_details: function (item) {
            ns.openWin('renwulist_equipment_off_details', '设备作业信息', {
                id: item.ID
            });
        },
        do_view: function (item,index) {
            var that = this;
            that.selectform=item;
            that.initaMapLBS();//获取当前定位
            //增加判断提示  当前线路需要按顺序执行巡查，请先完成对应巡查点。
            if (item.TaskStatus != "3") {
                if(item.RequireScan=="true"){
                    that.doUpdateLocation();//更新当前巡更地点
                    that.do_open_scan(item);
                    return;
                }        
            }
            that.open_details(item);
        },
        check_scan_result: function (id) {
            var that = this;
            if (!id) {
                ns.openFrame('scanner_frm', {
                    type: 10
                });
            }
            else {
                let selplantasksql = `SELECT * FROM Sys_PlanTask WHERE PlanTaskID=${that.form.ID} and EncriptID=='${id}'`;
                db.selectSql({
                    name: 'prodemotest',
                    sql: selplantasksql
                }, function (ret, err) {
                    if (ret.status) {
                        var tasklist = ret.data;
                        if (tasklist.length > 0) {
                            ns.openWin('renwulist_equipment_off_details', '设备作业信息', {
                                id: id
                            });
                        }
                        else{
                            api.toast({
                                msg: '二维码无效',
                                duration: 2000,
                                location: 'bottom'
                            });
                        }
                    }
                    else {
                        api.toast({
                            msg: err,
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                });

            };
        },
        // 初始化aMapLBS
        initaMapLBS() {
            let that = this;
            ns.confirmPer('location', function () {
                that.aMapLBSStart();
            });
        },
        // 开始定位并存储到本地
        aMapLBSStart() {
            let that = this;
            bmLocation.singleLocation({
                reGeocode: false,
                netWorkState: false
            }, function (ret) {
                // console.log(JSON.stringify(ret));
                if (ret.status) {
                    that.Longitude = ret.location.longitude;
                    that.Latitude = ret.location.latitude;
                    that.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber;
                }
            });
            //判断获取定位  没获取到每隔3秒再次获取
            if(!that.GPSLocation){
                setTimeout(function(){
                    that.initaMapLBS();
                },3000);
            }
            else{
                return;
            }  
        },
        doUpdateLocation:function(){
            var that=this;
            if(that.selectform.ID&&that.Longitude){
                let strsql=`UPDATE Sys_PlanTask SET Longitude='${that.Longitude}',Latitude='${that.Latitude}',GPSLocation='${that.GPSLocation}' WHERE ID=${that.selectform.ID}`;
                db.executeSql({
                    name: 'prodemotest',
                    sql: strsql
                }, function (ret, err) {        
                });
            }
        },
        onDealTaskTime:function(time){
            return ns.SetTime_style(time)
        },
        configManager: function () {
            bmLocation.configManager({
                // accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    app.form.ID = api.pageParam.id || 0;
    toast = new auiToast();
    bmLocation = api.require('bmLocation');
    db = api.require('db');
    ns.init_search();

    app.configManager();
    app.initaMapLBS();

    db.openDatabase({
        name: 'prodemotest'
    }, function(ret, err) {
        if (!ret.status) {
            api.toast({
                msg: err,
                duration: 2000,
                location: 'bottom'
            });
        } 
        else{
            app.get_item_data();
            app.get_data();
        }  
    });

    api.addEventListener({
        name: 'reloadtaskoff'
    }, function (ret, err) {
        app.get_data();
    });
  
    api.addEventListener({
        name: 'scandeviceqrcodedone'
    }, function (ret, err) {
        app.check_scan_result(ret.value.id);
    });

    api.addEventListener({
        name: 'home-refresh'
    }, function (ret, err) {
        app.get_data();
    });

    api.addEventListener({
        name:'viewdisappear'
    }, function(ret, err){        
        bmLocation.stopLocation();//取消定位
    });

    bmLocation.setAgreePrivacy({
        agree: true
    });
}
